package org.hepeng.workx.mybatis.util;

import org.apache.ibatis.plugin.Plugin;
import org.hepeng.workx.util.proxy.ProxyUtils;
import org.joor.Reflect;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @author he peng
 */
public class PluginUtils {

    public static boolean isPluginProxy(Object target) {
        Assert.notNull(target , "target must not be null");
        boolean isJdkProxy = ProxyUtils.isJdkProxy(target.getClass());
        if (isJdkProxy) {
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(target);
            if (Plugin.class.isAssignableFrom(invocationHandler.getClass())) {
                return true;
            }
        }
        return false;
    }

    public static Object getPluginTarget(Object obj) {
        if (isPluginProxy(obj)) {
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(obj);
            Object target = Reflect.on(invocationHandler).get("target");
            return getPluginTarget(target);
        }
        return obj;
    }
}
